#!/bin/bash

rm -rf build tmp
mkdir build tmp
cp -r ./*.ts tmp
cd tmp
find . -name '*.test.ts' | xargs rm -r
mv mod.ts index.ts
find . -name '*.ts' | xargs sed -i.bak 's/.ts";/";/g'
find . -name '*.ts' | xargs sed -i.bak 's/{ performance } = globalThis/{ performance } = "performance" in globalThis ? globalThis : require("perf_hooks")/g'
cp ../npm/tsconfig.json .
cp ../npm/.babelrc .
ln -s ../npm/node_modules node_modules
npx tsc -p tsconfig.json
npx babel . --extensions .ts -d ../build --ignore node_modules
cd ../build
jq 'del(.scripts,.private)' ../npm/package.json > package.json
for file in *.js; do
  BASE_NAME="$(basename -- "$file" .js)"
  mv -- "$file" "${BASE_NAME}.mjs"
  cat <<< $(jq ".exports[\"./${BASE_NAME}\"] = { \"require\": \"./${BASE_NAME}.js\", \"import\": \"./${BASE_NAME}.mjs\" }" package.json) > package.json
done
sed -E -i -e 's/from "([a-zA-Z\/\.]+)/from "\1\.mjs/g' *.mjs
sed -E -i -e 's/require\("perf_hooks"\)/{performance:{now:\(\)=>Date.now\(\)}}/g' *.mjs
sed -E -i -e 's/require\(([^)]+)\)/await import(\1)/g' *.mjs
cd ../tmp
cat <<< $(jq '.presets[0][1].modules = "cjs"' .babelrc) > .babelrc
cat .babelrc
npx babel . --extensions .ts -d ../build --ignore node_modules
cd ../build
echo -e "\nmodule.exports = Object.assign(exports.default || {}, exports);" | tee -a ./*.js
# patch for babel redefining exports
sed -E -i -e 's/if \(key in exports && .+/if \(key in exports\) return;/g' index.js
node ../scripts/rewriteStarExports.mjs
rm ./*-e
rm -r ../tmp
cp ../README.md .
cp ../LICENSE .
